package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ReceiveTextMessageHandle implements WxChatMsgHandler {

    @Resource
    private RedisUtil redisUtil;
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    private static final String KEY_WORD = "验证码";
    private static final String LOGIN_PREFIX = "loginCode";

    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到文本消息事件，");
        String Content = messageMap.get("Content");
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        if (KEY_WORD.equals(Content)) {

            Random random = new Random();
            int num = random.nextInt(900) + 100;
            //生成key：loginCode.验证码
            String numKey = redisUtil.buildKey(LOGIN_PREFIX,String.valueOf(num));
            //redis中存入key，value的值为openid，5分钟有效
            redisUtil.setNx(numKey,fromUserName,5l, TimeUnit.MINUTES);
            LocalDateTime now = LocalDateTime.now();
            String numContent = "您当前的验证码是：" + num + " " + "此验证码5分钟内有效";

            String replyContent = "<xml>\n" +
                    "<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "<CreateTime><![CDATA[" + now + "]]></CreateTime>\n" +
                    "<MsgType><![CDATA[text]]></MsgType>\n" +
                    "<Content><![CDATA[" + numContent + "]]></Content>\n" +
                    "</xml>";

            return replyContent;
        }
        return "<xml>\n" +
                "<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "<CreateTime>12345678</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA[请发送 "+" 验证码 "+"来获取验证]]></Content>\n" +
                "</xml>";
    }
}
